package com.dr.springboot.starter.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.Future;

/**
 * Created by rui on 2018/7/25.
 */
@Component
@Slf4j
public class AsyncTask {

    private static final Random random = new Random();

//    todo async 加上注解表明是一个异步方法
    @Async
    public Future task1() throws InterruptedException {
        log.info("task1 is running");
        long time = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        log.info("task1 finish. run:" + (System.currentTimeMillis() - time) + "ms");
        return new AsyncResult("task1");
    }

    @Async
//    todo async 通过future来将值返回
    public Future task2() throws InterruptedException {
        log.info("task2 is running");
        long time = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        log.info("task2 finish. run:" + (System.currentTimeMillis() - time) + "ms");
        return new AsyncResult("task2");

    }

    @Async
    public Future task3() throws InterruptedException {
        log.info("task3 is running");
        long time = System.currentTimeMillis();
        Thread.sleep(random.nextInt(10000));
        log.info("task3 finish. run:" + (System.currentTimeMillis() - time) + "ms");
        return new AsyncResult("task3");

    }
}
